package openfidias.maker.controller

import openfidias.maker.model.Model

/**
 * Represents a Data Access Object : DAO
 * @author atila
 */
class DataAccess extends Controller {

   DataAccess(Model model) {
      this.model = model
      _class = model._class.capitalize().plus("Dao")
   }

   String imports() {
      "import java.sql.Connection;${f.ret}"
      .plus("import java.sql.PreparedStatement;${f.ret}")
      .plus("import java.sql.ResultSet;${f.ret}")
      .plus("import java.sql.SQLException;${f.ret2}")

      .plus("import java.util.ArrayList;${f.ret}")
      .plus("import java.util.List;${f.ret2}")
   }

   /* CRUD : Create, Read, Update, Delete */

   String create() {
   """
   public void create(${model._class.capitalize()} ${model._class}) throws SQLException, Exception {
      PreparedStatement ps = null;
      ResultSet rs = null;
      try {
         Connection conn = Conexao.getInstance().getConexao();
         String query = "${model.queryCreate()}";
         ps = conn.preparedStatement(query);
         ${model.ps()}
         rs = ps.executeQuery();
         if ( rs.next() ) {
            ${model._class}.setId(rs.getLong("id"));
         }
         ps.close();
         rs.close();
      } catch(Exception e) {
         throw new Exception(e);
      }
   }
   """
   }

   String read() {

   }

   String update() {

   }

   String delete() {
   """
   public void delete(long id) throws SQLException, Exception {
      PreparedStatement ps = null;
      try {
         Connection conn = Conexao.getInstance().getConexao();
         String query = "${model.queryDelete()}";
         ps.setLong(1, id);
         ps.close();
      } catch(Exception e) {
         throw new Exception(e);
      }
   }
   """
   }
}

